var $$ = {},
    ajaxNumber = 0,
    ajaxUrl = '/dataApi';
    //ajaxUrl2 = '/zjzcApi';//测试
    ajaxUrl2="http://59.202.18.68:8585";//正式
    var scrollTimer="";
    var url_base_link = "http://192.2.2.31:8088/datav";//http://zjldjc.qicp.vip/datav/
$$.getRequestParams = function (urlStr) {
    if (typeof urlStr == "undefined") {
        var url = decodeURI(location.search); //获取url中"?"符后的字符串
    } else {
        var paramsStr = urlStr.split("?");
        if (paramsStr.length < 2) {
            return {};
        }
        var url = "?" + urlStr.substr(urlStr.indexOf('?') + 1);
    }
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            var name = strs[i].split("=")[0];
            theRequest[name] = decodeURI(strs[i].substr(strs[i].indexOf('=') + 1));
        }
    }
    return theRequest;
}

// 区划中心点
var areaCenter = {
    '330000':{ label: '浙江省', center:[120.153576, 29.289523], zooms:[7, 20] },
    '330100':{ label: '杭州市', center:[119.5258, 29.9882], zooms:9 },
    '330200':{ label: '宁波市', center:[121.5143, 29.7501], zooms:7 },
    '330300':{ label: '温州市', center:[120.5804, 27.9604], zooms:7 },
    '330400':{ label: '嘉兴市', center:[120.7837, 30.619 ], zooms:7 },
    '330500':{ label: '湖州市', center:[119.9048, 30.7654], zooms:7 },
    '330600':{ label: '绍兴市', center:[120.6573, 29.7691], zooms:7 },
    '330700':{ label: '金华市', center:[119.9762, 29.1713], zooms:7 },
    '330800':{ label: '衢州市', center:[118.7073, 28.9216], zooms:7 },
    '330900':{ label: '舟山市', center:[122.106863,30.016028], zooms:7 },
    '331000':{ label: '台州市', center:[121.1353, 28.8591], zooms:7 },
    '331100':{ label: '丽水市', center:[119.6082, 28.2318], zooms:7 }
}

$$.handleActivityName = function(name) {
    if(name == "提交立案审批"){
        return "立案";
    } else if(name == "提交结案审批"){
        return "结案";
    } else {
        return name;
    }
}

// 处理区级区划传入
$$.handleQXCode = function (areaCode){
    if(areaCode[4] != 0 || areaCode[5] != 0){
        return areaCode.substr(0,4) + "00";
    } else {
        return areaCode
    }
}

// 判断是否非区县级areacode
$$.isQXCode = function (areaCode){
    if(areaCode == "" || areaCode == null){
        return false;
    } else if(areaCode[4] != 0 || areaCode[5] != 0){
        return true;
    } else {
        return false;
    }
}

//获取地址栏参数 duge true-查#后面参数  false/空-查?后面参数
$$.localName = function (name, duge) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    if (duge) {
        var r = location.hash.substr(1).match(reg);
    } else {
        var r = location.search.substr(1).match(reg);
    }
    if (r != null) return decodeURI(r[2]);
    return null;
};

//将地区代码转化成完整的参数
$$.getFullAreaCode = function (areaCode) {
    if(areaCode.length == 2){
        return areaCode +"0000";
    } else if(areaCode.length == 4){
        return areaCode +"00";
    } else {
        return areaCode;
    }
};

//分页调用
$$.pagination = function (data) {
    //elem-dom对象或者id(不用加#) count-总数 limit-每页条数 jump-分页触发回调
    layui.use('laypage', function () {
        var laypage = layui.laypage;
        laypage.render({
            theme: '#2a88fc',
            elem: data.elem,
            groups: data.groups || 3,
            limit: data.limit || 7,
            count: data.count || '',
            layout: ['count', 'prev', 'page', 'next', 'refresh', 'skip'],
            jump: function (obj, first) {
                if (data.jump) {
                    data.jump(obj, first);
                }
            }
        });
    });
};

function setybp(id,optionData){
    var myChart=echarts.init($(id)[0])
    var optionData =optionData || {
        title: '已投资',
        legendData: ['已投资', '年总投资'],
        progress: {
            colorStops: ['#46d7a2', '#92ffd8'],
        },
        detail: {
            color: '#43D5A0',
        },
        axisTick: {
            color: 'rgba(67, 213, 160,.25)',
        },
        axisLine: {
            color: ['rgba(67, 213, 160, 0.25)', 'rgba(67, 213, 160, 0)'],
        },
        value: 50,
    };
    var option = {
        legend: {
            show:false
        },
        series: [
            // 背景
            {
                animation: false,
               
                type: 'gauge',
                radius: '112%', // 位置
                center: ['52%', '75%'],
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 12,
                // 展示当前进度
                progress: {
                    show: true,
                    width: 12,
                    itemStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [
                                {
                                    offset: 0,
                                    color: 'rgba(255,255,255,0.15)', // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(255,255,255,0.15)', // 100% 处的颜色
                                },
                            ],
                            global: false, // 缺省为 false
                        },
                    },
                },
                // 仪表盘指针
                pointer: {
                    show: false,
                },
                // 仪表盘轴线相关配置
                axisLine: {
                    show: false,
                },
                // 刻度样式
                axisTick: {
                    show: false,
                },
                // 分隔线样式
                splitLine: {
                    show: false,
                },
                // 刻度标签
                axisLabel: {
                    show: false,
                    distance: 16,
                    formatter: function (value) {
                        if (value === 100) {
                            return value + '%';
                        }
                        return '';
                    },
                    color: 'rgba(255,255,255,.85)',
                    fontSize: 12,
                },
                // 表盘中指针的固定点
                anchor: {
                    show: false,
                },
                detail: {
                    lineHeight: 40,
                    borderRadius: 8,
                    offsetCenter: ['0%', '30%'],
                    fontSize: 12,
                    fontWeight: 'bolder',
                    formatter: function (value) {
                        return optionData.title;
                    },
                    color: '#fff',
                },
                data: [
                    {
                        value: 100,
                    },
                ],
            },
            // 内容
            {
              
                type: 'gauge',
                radius: '112%', // 位置
                center: ['52%', '75%'],
                startAngle: 180,
                endAngle: 0,
                min: 0,
                zlevel: 10,
                max: 100,
                splitNumber: 12,
                // 展示当前进度
                progress: {
                    show: true,
                    width: 12,
                    itemStyle: {
                        color:new echarts.graphic.LinearGradient(
                            0, 0, 0, 1,
                            [
                                {offset: 0, color: optionData.progress.colorStops[0]},
                                {offset: 0.4, color: optionData.progress.colorStops[1]},
                                {offset: 1, color: optionData.progress.colorStops[1]}
                            ]
                        )
                        // color: {
                        //     type: 'linear',
                        //     x: 0,
                        //     y: 0,
                        //     x2: 0,
                        //     y2: 1,
                        //     colorStops: [
                        //         {
                        //             offset: 0,
                        //             color: optionData.progress.colorStops[0], // 0% 处的颜色
                        //         },
                        //         {
                        //             offset: 0.3,
                        //             color: optionData.progress.colorStops[1], // 0% 处的颜色
                        //         },
                        //         {
                        //             offset: 1,
                        //             color: optionData.progress.colorStops[1], // 100% 处的颜色
                        //         },
                        //     ],
                        //     global: false,
                        // },
                    },
                },
                // 仪表盘指针
                pointer: {
                    show: false,
                },
                // 仪表盘轴线相关配置
                axisLine: {
                    show: false,
                    lineStyle: {
                        color: [[1, '#304c60']],
                        width:35,
                    },
                },
                // 刻度样式
                axisTick: {
                    distance: -45,
                    length:3,
                    lineStyle: {
                        width: 1,
                        color: optionData.axisTick.color,
                    },
                },
                // 分隔线样式
                splitLine: {
                    show: false,
                },
                // 刻度标签
                axisLabel: {
                    show: false,
                },
                // 表盘中指针的固定点
                anchor: {
                    show: false,
                },
                detail: {
                    lineHeight: 40,
                    borderRadius: 8,
                    offsetCenter: ['0%', '-18%'],
                    fontSize:$$.fitFontSize(22),
                    fontWeight: 'bolder',
                    formatter: function (value) {
                        return value + '%';
                    },
                    color: optionData.detail.color,
                },
                data: [
                    {
                        value: optionData.value,
                    },
                ],
            },
          
            // 中间渐变背景
            {
                type: 'gauge',
                radius: '76%', // 位置
                center: ['52%', '75%'],
                min: 0,
                max: 100,
                startAngle: 180,
                endAngle: 0,
                axisLine: {
                    show: true,
                    lineStyle: {
                        // 轴线样式
                        width: 300, // 宽度
                        color: [
                            [
                                1,
                                new echarts.graphic.RadialGradient(0.5, 1, 1, [
                                    {
                                        offset: 1,
                                        color: optionData.axisLine.color[0],
                                    },
                                    {
                                        offset: 0,
                                        color: optionData.axisLine.color[1],
                                    },
                                ]),
                            ],
                        ],
                    },
                },
                axisTick: {
                    // 刻度
                    show: false,
                },
                splitLine: {
                    // 分割线
                    show: false,
                },
                axisLabel: {
                    // 刻度标签
                    show: false,
                },
                pointer: {
                    // 仪表盘指针
                    show: false,
                },
                detail: {
                    // 仪表盘详情
                    show: false,
                },
            },
        ],
    };
    myChart.setOption(option)
    }
$$.alert = function (content, mainClass) {
    mainClass = mainClass || '';
    var ids = 'tac' + (new Date()).valueOf(),
        html;
    if (content) {
        if (content == 'table') {
            html = '<div data-i="'+ids+'" class="tac_box tac_table_box ' + mainClass + '"><div class="close"></div><div class="conment"></div><table  id="' + ids + '"  lay-filter="' + ids + '"></table></div>'
        } else if (content == 'img' || content == 'tableTwo') {
            html = '<div data-i="'+ids+'" class="tac_box tac_img_box ' + mainClass + '"><div class="close"></div><div id="' + ids + '" class="conment"></div></div>'
        } else if (content == 'axzs') {
            html = '<div data-i="'+ids+'" class="tac_box tac_axzs ' + mainClass + '"><div class="close"></div><div id="' + ids + '" class="conment"></div></div>'
        } else {
            html = '<div data-i="'+ids+'" class="tac_box tac_' + content + '"><div class="close"></div><div id="' + ids + '" class="conment"></div></div>'
        }
    } else {
        html = '<div data-i="'+ids+'" class="tac_box tac_table_box ' + mainClass + '"><div class="close"></div><div id="' + ids + '" class="conment"></div></div>'
    }
    $('body').append(html);
    var length = $('.tac_box').length;
    var zIndex;
    if (length > 1) {
        zIndex = $('.tac_box').eq(length - 2).css('z-index')-0;
        $('#' + ids).parent().css('z-index', zIndex+1);
    }
    $('body').append('<div class="tanc_mask mask_'+ids+'" style="z-index:'+(zIndex||98)+';"></div>');
    return ids;
}
$('.tac_box .close').live('click', function () {
    $(this).parent().remove();
    var ids = $(this).parent().attr('data-i');
    $('.tanc_mask.mask_'+ids+'').remove();
})
function setWDPHB(config) {
    if(config.autoScroll){
        clearInterval(scrollTimer)
    }
    var id=config.tableId||''
    var columns = config.columns || []
    var datas = config.data || [];
    var html = '<div class="wdpm_table" >';
    var head_html_ = `<div class="wd_sort_tabs">`
    $.each(columns, function (i, item) {
        if (item.type != "hide") {
            head_html_ += ` <div class="wd_sort_tab_item dxpl"  style="color:${config.tdColor==i?'#25CEFF':"#fff"};width:${item.widthBl?item.widthBl:''}" title="${item.title}">${item.title}</div>`
        }
    })
    head_html_ += `</div>`
    $.each(datas,function (i,item) {
        html += `<div class="wdpm_table_item"><div class="tr active" wd_${item.sc01_name_1}>`
        $.each(columns, function (j, jItem) {
             var trColor="#fff"
            if (jItem.type != "hide") {
                html += `<div class="td co_${j}" title="${jItem.type == 'index' ? i + 1 : (item[jItem.field] || '')}${jItem.unit ? jItem.unit : ''}" style="color:${trColor};width:${jItem.widthBl?jItem.widthBl:''}"">${jItem.type == 'index' ? i + 1 : (item[jItem.field] || '')}${jItem.unit ? jItem.unit : ''}</div>`
            }
        })
        html += `</div> </div>`
    });
    html += `</div>`
    $(id).html(head_html_ + html);
    $(id).find('.wdpm_table_item').click(function(){
        var index = $(this).index();
        config.clickFun && config.clickFun({
            data: datas[index]
        })
    })
    $(id + ' .dxpl').click(function () {
        var index=$(this).index();
       var params=columns[index].params
       config.tdColor=index
         if(params){
                $$.ajaxRequest(ajaxUrl + '/getDataByForward',params, function (res) {
                    config.data = " "
                    config.data = res.data
                    setWDPHB(config)
             })
         }
        
      
    })
    if(config.autoScroll){
        scrollTimer = setInterval(() => {
            autoScroll(id);
         },1500);
    }
    //表格滚动
function autoScroll(obj) {
    console.log(obj,"hj")
    const $self =$(obj).find('.wdpm_table');
    const outerHeight = $self.find('.wdpm_table_item:first').height();
    // 改变table的margin-top，定时将第一行tr挪至（列表）最后
     $self.animate({'marginTop': -outerHeight + 'px'},500, () => {
      $self.css({margin: 0}).find('.wdpm_table_item:first').appendTo($self);
    });
  }
    // $('.wd_'+areaCode).addClass('active').siblings().removeClass('active');//右侧排行榜高亮
}
//数据表格
/*
 *id:主键
 * data:表头
 * url:请求路径
 * request:请求参数
 * height：表格高度
 * */
$$.table = function (data) {
    //id, colsData, url, request, height, datarequ, doneFun, datas, pageProp,rowClickFun,toolFun
    layui.use('table', function () {
        var table = layui.table;
        if (!data.pageProp) {
            pageProp = {
                limit: 8
            }
        }
        if (data.url) {
            var tableRenderData = {
                elem: data.id || '',
                filter: data.id || '',
                height: data.height,
                url: data.url,
                loading: false,
                page: {
                    layout: ['prev', 'page', 'next',],
                    groups: 5,
                    limit: (data.pageProp && data.pageProp.limit) || 10
                    // first: true ,
                    // 					// last: true
                },
                response: {
                    // statusCode: 'ok'
                    statusCode: true
                },
                parseData: function (res) {
                    return {
                        "code": res.success, //解析接口状态
                        ///"msg": res.state, //解析提示文本
                        "count": res.data.totalrow, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                },
                cols: data.colsData,
                where: data.where,
                request: {
                    pageName: 'pageNumber',
                    limitName: 'pageSize'
                },
                id: data.id,
                done: data.doneFun
            }
            table.render(tableRenderData);

        } else {
            table.render({
                elem: data.id || '',
                height: data.height,
                page: true,
                cols: data.data,
                id: data.id,
                data: data.datas || [],
            });

        }
        table.on('row(' + (data.id.replace('#', '')) + ')', function (obj) {
            data.rowClickFun && data.rowClickFun(obj)
        });
        table.on('tool(' + (data.id.replace('#', '')) + ')', function (obj) {
            data.toolFun && data.toolFun(obj)
        });

    });
}

// $$.table=function(data){
// 	//id,data,url,request,height,datarequ,doneFun,datas
// 	var tableRenderData = {};
// 	for(var k in data){
// 		tableRenderData[k] = data[k];
// 	}
// };
//table重新渲染
$$.tableReload = function (id, url, where) {
    layui.use('table', function () {
        var table = layui.table;
        table.reload(id, {
            url: url,
            where: where //设定异步数据接口的额外参数
        });
    });
}
//请求数据
$$.ajaxRequest = function (url, data, successFun, errorFun, type_, isAsync) {
    ajaxNumber++;
    $.support.cors = true; //为ie下使用
    $.ajax({
        type: type_ || 'post',
        url: url,
        data: data || '',
        dataType: 'json',
        async: isAsync === undefined ? true : isAsync,
        //timeout: 20000,
        success: function (result) {
            if (result && typeof result == "string") {
                result = eval("(" + result + ")");
            }

            if (result && result.code == '-22') {
                $$.clearUserInfo();
                return false;
            }

            if (successFun) {
                successFun(result);
            }
        },
        error: function (result) {
            if (result && typeof result == "string") {
                result = eval("(" + result + ")");
            }
            result = result.responseText;
            if (errorFun) {
                errorFun(result);
            }
        }
    });
};
//设置cookies
$$.saveCookies = function (name, value) {
    var Days = 365,
        exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + encodeURI(value) + ";expires=" + exp.toGMTString() + ";path=/";
};
//清除cookies信息
$$.clearCookies = function (name) {
    var d = new Date();
    d.setTime(d.getTime() + (-365 * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = name + "=0;path=/;" + expires;
}

function getViewFontSize(curSize) {
    var width = $(document).width();

    var fontSize = width < 1920 ? 12 : 0.0085 * width;
    return fontSize
}

function getMonthArr(curQS, len, isInclude) { //返回前六个月，不包含当月
    /*
    curQS,len,isInclude => 当前期数（201911），几个月， 是否包含本月
    201911 => ["201910", "201909", "201908", "201907", "201906", "201905"]
    201902 => ["201901", "201812", "201811", "201810", "201809", "201808"]
    */
    len = len || 6;
    isInclude = (typeof isInclude == "undefined" ? false : isInclude);
    var year = curQS.slice(0, 4),
        month = curQS.slice(4, 6),
        monthArr = [],
        i = 0,
        flag = 0,
        item = '';
    if (isInclude) {
        while (monthArr.length < len) {
            if (month - 0 < len && month - i == 0) {
                flag = i;
            }
            item = month - 0 >= len ? (year + (month - i >= 10 ? month - i : '0' + (month - i))) : (month - i > 0 ? (year + (month - i >= 10 ? month - i : '0' + (month - i))) : (year - 1 + '' + (12 - (i - flag) >= 10 ? 12 - (i - flag) : '0' + (12 - (i - flag)))))
            monthArr.push(item);
            i++;
        }
    } else {
        while (monthArr.length < len) {
            if (month - 0 <= len && month - (i + 1) == 0) {
                flag = i;
            }
            item = month - 0 > len ? (year + ((month - (i + 1)) >= 10 ? (month - (i + 1)) : '0' + (month - (i + 1)))) : (month - (i + 1) > 0 ? (year + ((month - (i + 1)) >= 10 ? (month - (i + 1)) : '0' + (month - (i + 1)))) : ((year - 1 + '') + ((12 - (i - flag) >= 10) ? (12 - (i - flag)) : ('0' + (12 - (i - flag))))))
            monthArr.push(item);
            i++;
        }
    }

    return monthArr.sort(function (a, b) {
        return a - b;
    });
}

$$.formatDate = function (dateStr, split, isTime) {
    split = split || '-';
    if (dateStr) {
        var date = new Date(dateStr);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        if (isTime) {
            return y + split + m + split + d + ' ' + h + ':' + minute + ':' + second;
        } else {
            return y + split + m + split + d;
        }

    } else {
        return dateStr
    }

}
$$.transVHFontSize = function (vhData) {
    var vHeight = window.innerHeight;
    return Math.floor(vHeight * vhData / 100)
}
$$.transFontSize = function (pxData) {
    var vHeight = window.innerHeight;
    return Math.floor(vHeight * pxData / 1080)
}
$$.fitFontSize = function(px){
    // var vHeihgt = document.documentElement.clientHeight;
    var vHeihgt = window.innerHeight;
    // var vHeihgt = $(document).height();
    return px * vHeihgt / 1080;
}

$$.alertTable = function (data, mainClass) { //弹出表格
    data.type = data.type || 'table';
    data.tabDatas = data.tabDatas || [];
    var ecm = $$.alert(data.type, mainClass,data.hideCloseBtn);
    if (data.type == 'table') {
        var tableHead = '';
        tableHead = '<div class="table_head">' +
            '    <div class="title"></div>' +
            '    <div class="tabs"></div>' +
            '</div>';
        var formHTML = '';
        if(data.searchColumn && data.searchColumn.length>0){
            formHTML = `<div class="search_column"><form class="layui-form" action="" lay-filter="allUnitsForm">`
           $.each(data.searchColumn,function(i,item){
            if(item.type == 'select'){
                var selectHTML = '';
                $.each(item.dicData,function(i,item){
                    selectHTML += `<option value="${item.value}">${item.label}</option>`;
                })
                formHTML += `<div class="layui-inline">
                            <label class="layui-form-label">${item.name}</label>
                            <div class="layui-input-inline">
                                <select name="${item.field}" lay-verify="">
                                    <option value="">请选择</option>
                                    ${selectHTML}
                                </select>  
                            </div>
                        </div>`;
            }else if (item.type == 'datePicker'){
                formHTML += `<div class="layui-inline">
                                <label class="layui-form-label">${item.name}</label>
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" data-type="datePicker" data-index="${i}" id="${item.field}" />
                                </div>
                            </div>`;
            }else if (item.type == 'dropdown'){
                formHTML += `<div class="layui-inline">
                                <label class="layui-form-label">${item.name}</label>
                                <div class="layui-input-inline">
                                    <div class="layui-input"  data-type="dropdown" data-index="${i}" id="${item.field}" ><div class="text text_overflow">请选择</div><i class="layui-icon layui-icon-down layui-font-12"></i></div>
                                </div>
                            </div>`;
            }else if(item.type == 'tree'){
                formHTML += `<button class="layui-btn" id="demo1">
                ${item.name}
                <i class="layui-icon layui-icon-down layui-font-12"></i>
              </button>`
            }else{
                formHTML += `<div class="layui-inline">
                            <label class="layui-form-label">${item.name}</label>
                            <div class="layui-input-inline">
                                <input type="text" name="${item.field}" placeholder="请输入" autocomplete="off" class="layui-input" />
                            </div>
                        </div>`;
            }
           });
           formHTML += '<button lay-submit class="layui-btn layui-btn-normal" lay-filter="allUnitsForm">查询</button>   </form></div>'
        }
        $('#' + ecm).parent().find('.conment').html(tableHead);
        $('#' + ecm).parent().find('.conment .table_head .title').html(data.title || '');
        $('#' + ecm).parent().find('.conment').append(formHTML);
        // layui.use(['jquery', 'laydate', 'layedit', 'form','dropdown'], function () {
        layui.use(['jquery', 'laydate', 'layedit', 'form'], function () {
            //dropdown = layui.dropdown
            var form = layui.form, $ = layui.jquery,laydate = layui.laydate;
            form.render();
            form.render('select', 'allUnitsForm');
            $('#' + ecm).parent().find('[data-type="datePicker"]').each(function(i,ele){
                var index= $(this).attr('data-index');
                laydate.render({
                    elem: '#'+data.searchColumn[index].field,
                    type: data.searchColumn[index].subtype,
                    range: data.searchColumn[index].range||false,
                    format:  data.searchColumn[index].format,
                    done: function(value, date, endDate){
                        //aae036StartTime/aae036EndTime
                        // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                        // console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                        var startTime = {
                            year: date.year||'',
                            month: date.month?moreThanTen(date.month):'',
                            date: date.date?moreThanTen(date.date):''
                        };
                        var endTime = {
                            year: endDate.year||'',
                            month: date.month?moreThanTen(endDate.month):'',
                            date: date.date?moreThanTen(endDate.date):''
                        };
                        if(data.searchColumn[index].range){
                            
                            data.where[data.searchColumn[index].field+'StartTime'] = startTime.year + startTime.month + startTime.date;
                            data.where[data.searchColumn[index].field+'EndTime'] = endTime.year + endTime.month + endTime.date;
                        }else{
                            data.where[data.searchColumn[index].field] = startTime.year + startTime.month + startTime.date;
                            // data.where[data.searchColumn[index].field] = endTime.year + endTime.month + endTime.date;
                        }
                      
                    }
                  });
            })
            $('#' + ecm).parent().find('[data-type="dropdown"]').each(function(i,ele){
                var index= $(this).attr('data-index');
                // dropdown.render({
                //     elem: '#'+data.searchColumn[index].field,
                //     data: data.searchColumn[index].dicData,
                //     click: function(obj){
                //         $(ele+' .text').text(obj.title)
                //         data.where[data.searchColumn[index].field] = obj.id;
                //     },
                //   });
                //   return;
                renderDropdown({
                    elem: '#'+data.searchColumn[index].field,
                    data: data.searchColumn[index].dicData,
                    textclick: function(obj){
                        $(ele).find(' .text').text(obj.title)
                        data.where[data.searchColumn[index].field] = obj.id;
                    },
                    iconClick:function(){
                        
                    }
                  });

            })
            form.on('submit(allUnitsForm)', function(formData){
                console.log(formData.field) //当前容器的全部表单字段，名值对形式：{name: value}
                $.each(formData.field,function(k,val){
                    data.where[k] = val;
                })
                initTable();
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
              });
        })
        if (data.tabDatas && data.tabDatas.length > 0) {
            var tabHtml = '';
            $.each(data.tabDatas, function (i, item) {
                tabHtml += '<div class="tab_item">' + item.text + '</div>';
            })
            tableHead = '<div class="table_head">' +
                '    <div class="title"></div>' +
                '    <div class="tabs">' +
                tabHtml +
                '    </div>' +
                '</div>';
            $('#' + ecm).parent().find('.conment .table_head .tabs').html(tabHtml)
            $('#' + ecm).parent().find('.conment .tabs .tab_item').eq(data.activeTab || 0).addClass('active');

            initTable(data.activeTab || 0)
            $('#' + ecm).parent().find('.conment .tabs .tab_item').on('click', function () {
                var index = $(this).index();
                $(this).addClass('active').siblings().removeClass('active');
                initTable(index)
            })
        } else {
            initTable();
        }
    } else if (data.type == 'tableTwo') {
        $('#' + ecm).html('<div class="title">'+(data.title || '')+'</div><div class="table_con"></div>')
        $$.ajaxRequest(data.url,data.where||{},function(res){
            $$.title2Table('#'+ecm+' .table_con', data.colsData, res.data||{},data.colsNum)
        })
        
    }
    function initTable(index) {
        var tableParams = {
            id: '#' + ecm,
            colsData: data.colsData || [], //表头
            data: data.datas || [], //表头
            datas: data.datas || [], //表头
            url: data.url, //接口地址
            where: data.where || (data.tabDatas.length > 0 && data.tabDatas[index] && data.tabDatas[index].params || {}), //除分页外，接口需要的参数/tab选项卡传入
            pageProp: data.pageProp || {
                limit: 10
            }, //分页参数 默认每页10条
            doneFun: data.doneFun,
            rowClickFun: data.rowClickFun || null, //行点击事件
            toolFun: data.toolFun || null //td 点击事件，先在columnsDatas中绑定事件
        };
        if (data.tabDatas.length > 0 && data.tabDatas[index] && data.tabDatas[index].colsData) {
            tableParams.colsData = data.tabDatas[index].colsData
        }
        $$.table(tableParams);
    }
}


function renderDropdown(config){
    // var html = '';
    // html += '<div class="my_dropdown">';
    // html += '<ul class="dropdown_menu layui-panel">'
    // html += renderDropdownChild(config.data)
    // html += '</ul';
    // html += '</div';
    $(config.elem).append(renderDropdownChild(config.data));
    $(config.elem).click(function(){
        $(this).children('.my_dropdown').toggle();
    })
    $(document).not(config.elem).click(function(){
        $(config.elem).children('.my_dropdown').hide();
    })
    $(config.elem).find('.menu_title').off('click').click(function(e){
        $(config.elem).find('.my_dropdown').hide();
        config.textclick({
            id: $(this).parent().attr('data-i'),
            title: $(this).text()
        })
        e.stopPropagation();
    })
    $(config.elem).find('.menu_child_icon').off('click').click(function(e){
        $(this).siblings('.my_dropdown_child').show();
        e.stopPropagation();
    })
    
    

}
function renderDropdownChild(data){
    var html = '';
    var isParent = !data[0].pid;
    html += '<div class="my_dropdown '+(isParent?'':'my_dropdown_child')+'">';
    html += '<ul class="dropdown_menu '+(isParent?'':'dropdown_menu_child')+'">'
    $.each(data,function(i,item){
        html += '<li class="dropdown_menu_item layui-menu-body-title" data-i="'+(item.id)+'">'+('<div class="menu_title text_overflow"  title="'+item.title+'">'+item.title+'</div>')+(item.child&&item.child.length>0?'<i class="menu_child_icon layui-icon layui-icon-right"></i>':'');
        if(item.child&&item.child.length>0){
            html += (renderDropdownChild(item.child));
        }
        html +='</li>'
    })
    html += '</ul>';
    html += '</div>';
    return html;
}

$$.ajaxRequestAsyncFalse = function (url, data, successFun, errorFun, type_) {
    ajaxNumber++;
    $.support.cors = true; //为ie下使用
    $.ajax({
        type: type_ || 'post',
        url: url,
        data: data || '',
        dataType: 'json',
        async: false,
        //timeout: 20000,
        success: function (result) {
            if (result && typeof result == "string") {
                result = eval("(" + result + ")");
            }

            if (result && result.code == '-22') {
                $$.clearUserInfo();
                return false;
            }

            if (successFun) {
                successFun(result);
            }
        },
        error: function (result) {
            if (result && typeof result == "string") {
                result = eval("(" + result + ")");
            }
            result = result.responseText;
            if (errorFun) {
                errorFun(result);
            }
        }
    });
};
$$.alertTabTable = function (data, mainClass) { //弹出表格
    data.type = data.type || 'img';
    data.tabDatas = data.tabDatas || [];
    var ecm = $$.alert(data.type, mainClass,data.hideCloseBtn);
    var title = '<div class="table_head"><div class="title"></div></div>'
    var container = '<div class="container">' +
        '    <div class="table_tablist"></div>' +
        '    <div class="content"></div>' +
        '</div>';
    $('#' + ecm).html(title + container);
    $('#' + ecm).find('.title').html(data.title || '');
    if (data.tabDatas && data.tabDatas.length > 0) {
        //渲染左侧tab
        var tabHtml = '', contentHtml = '';
        $.each(data.tabDatas, function (i, item) {
            tabHtml += '<div class="tab_item">' + (item.text||'') + '<span class="num"></span></div>';
            // contentHtml += '<div class="tab_content" >' + i + '内容内容内容内容内容内容内容内容</div>';
            contentHtml += '<div class="tab_content" ></div>';
        });
        if(data.tabDatas.length>1){
            $('#' + ecm).find('.table_tablist').html(tabHtml);
        }
        $('#' + ecm).find('.content').html(contentHtml);
        $('#' + ecm).find('.table_tablist .tab_item').eq(data.activeTab || 0).addClass('active');
        $('#' + ecm).find('.content .tab_content').eq(data.activeTab || 0).addClass('active')
        // renderContent(0)
        var renderIndex = 0;
        var renderTimer = setInterval(function(){
            renderContent(renderIndex);
            renderIndex++;
            if(renderIndex >= data.tabDatas.length){
                clearInterval(renderTimer);
            }
        },100);
        // renderContent(data.activeTab || 0)
        $('#' + ecm).find('.table_tablist .tab_item').on('click', function () {//tab点击事件
            var index = $(this).index();
            // renderContent(index)
            $(this).addClass('active').siblings().removeClass('active');
            $('#' + ecm).find('.content .tab_content').eq(index).addClass('active').siblings().removeClass('active');
        });
        

    }
    function renderContent(iTab) {
        var contentEle = $('#' + ecm).find('.content .tab_content').eq(iTab);
        if(contentEle.find('.table_head').length > 0){
            return;
        }else{
            contentEle.html('');//清空tab对应content的内容
            tabItem = data.tabDatas[iTab];
            if (tabItem.tableDatas && tabItem.tableDatas.length > 0) {
                $.each(tabItem.tableDatas, function (iTable, tableItem) {//table数据
                    tableItem.type = tableItem.type || 'table';

                    if (tableItem.type == 'table') {
                        var tableHead = '';
                        tableHead = '<div class="table_head">' +
                            '    <div class="title">' + (tableItem.title || '') + '</div>' +
                            '    <div class="tabs">' +
                            '    </div>' +
                            '</div>';
                        contentEle.append(tableHead);
                        var tableId = 'tableConecm'+ecm + iTab + iTable;
                        contentEle.append('<div id="' + tableId + '" lay-filter="' + tableId + '"></div>');
                        if (tableItem.tabDatas && tableItem.tabDatas.length > 0) {
                            var tabHtml = '', tableHead = '';
                            $.each(tableItem.tabDatas, function (i, item) {
                                tabHtml += '<div class="tab_item">' + item.text + '</div>';
                            })
                            contentEle.find('.table_head').eq(iTable).find('.tabs').html(tabHtml)
                            contentEle.find('.table_head').eq(iTable).find('.tabs .tab_item').eq(tableItem.activeTab || 0).addClass('active');
                            initTable('#' + tableId, tableItem.activeTab || 0, tableItem)
                            // console.log( contentEle.find('.table_head').eq(iTable));return;
                            contentEle.find('.table_head').eq(iTable).find('.tabs .tab_item').on('click', function () {
                                var index = $(this).index();
                                $(this).addClass('active').siblings().removeClass('active');
                                initTable('#' + tableId, index, tableItem);
                            })
                        } else {
                            initTable('#' + tableId, 0, tableItem)
                        }
                    } else if (tableItem.type == 'tableTwo') {
                        var tableHead = '';
                        tableHead = '<div class="table_head">' +
                            '    <div class="title">' + (tableItem.title || '') + '</div>' +
                            '    <div class="tabs">' +
                            '    </div>' +
                            '</div>';
                        contentEle.append(tableHead);
                        var tableId = 'tableCon' + iTab + iTable;
                        contentEle.append('<div id="' + tableId + '" class="datalist"></div>');
                        if (tableItem.tabDatas && tableItem.tabDatas.length > 0) {
                            var tabHtml = '';
                            $.each(tableItem.tabDatas, function (i, item) {
                                tabHtml += '<div class="tab_item">' + item.text + '</div>';
                            })

                            tableHead = '<div class="table_head">' +
                                '    <div class="title"></div>' +
                                '    <div class="tabs">' + tabHtml + '</div>' +
                                '</div>';
                            contentEle.find('.table_head').eq(iTable).find('.tabs').html(tabHtml);
                            contentEle.find('.table_head').eq(iTable).find('.tabs .tab_item').eq(tableItem.activeTab || 0).click();
                            contentEle.find('.table_head').eq(iTable).find('.tabs .tab_item').live('click', function () {
                                var index = $(this).index();
                                $(this).addClass('active').siblings().removeClass('active');
                                initTableTwo('#' + tableId, tableItem);
                            })
                        } else {
                            initTableTwo('#' + tableId, tableItem)
                        }
                    }

                })
            } else {
                if (tabItem.type == 'iframe') {
                    var paramsArr = [], src = '';
                    $.each(tabItem.params, function (k, val) {
                        var str = '&' + k + '=' + val;
                        paramsArr.push(str)
                    })
                    src = tabItem.src + '?iframe=true' + paramsArr.join('');
                    contentEle.append('<iframe  src="' + src + '" style="width: 100%;height: 98%;"></iframe>');
                } else {
                    contentEle.append('<span class="zwsj">暂无该类信息</span>');
                }
            }
        }
    }

    function initTable(id, index, data) {
        var tableParams = {
            id: id,
            colsData: data.colsData || [], //表头
            data: data.datas,
            datas: data.datas,
            url: data.url, //接口地址
            where: data.where, //除分页外，接口需要的参数/tab选项卡传入
            pageProp: data.pageProp || {
                limit: 10
            }, //分页参数 默认每页10条
            doneFun: data.doneFun,
            rowClickFun: data.rowClickFun || null, //行点击事件
            toolFun: data.toolFun || null //td 点击事件，先在columnsDatas中绑定事件
        };
        if (data.tabDatas && data.tabDatas[index] && data.tabDatas[index].colsData) {
            tableParams.colsData = data.tabDatas[index].colsData
        }
        if (data.tabDatas && data.tabDatas[index] && data.tabDatas[index].params) {
            tableParams.where = data.tabDatas[index].params
        }
        $$.table(tableParams);
    }

    function initTableTwo(id, data) {
        setTimeout(function () {
            $$.ajaxRequestAsyncFalse(data.url, data.where, function (res) {
                if (res) {
                    var levels = data.resultObj.split('.');
                    var obj = res;
                    $.each(levels, function () {
                        obj = obj[this];
                    });
                    $$.title2Table(id, data.colsData, obj);
                } else {
                    $$.title2Table(id, data.colsData, {});
                }

            })
        }, 100);

    }
}

$$.title3Table = function (id, colArr, obj,colsNum) {
    var html = '';
    colArr = colArr || [];
    obj = obj || {};
    var singleLength = 0,colsNum = colsNum||2;
    for (var i = 0; i < colArr.length; i++) {
        if(colArr[i].fitWidth){
            if (singleLength % colsNum != 0){
                html += '</div>';
            }
            singleLength = 0;
            html += '<div class="row">';
            if(colArr[i].type && colArr[i].type == 'img'){
                var imgs = obj[colArr[i].field].split(',');
                html += '<div class="col_'+colsNum+' fit_Width"><span class="th">' + colArr[i].title + '</span>';
                html += '<div class="imgs_con">'
                $.each(imgs,function(i,item){
                    html += '<img class="img" src="'+(item)+'" width="80px"/>'
                })
                html += '</div>'
                html += '</div>';
            }else{
                html += '<div class="col_'+colsNum+' fit_Width"><span class="th">' + colArr[i].title + '</span><span>' + (obj[colArr[i].field] || '') + (colArr[i].suffix ? colArr[i].suffix : '') + '</span></div>';
            }
            html += '</div>';
            // console.log(singleLength)

        }else{
            // console.log(singleLength)
            singleLength++;
            if (singleLength % colsNum == 1){
                html += '<div class="row">';
                html += '<div class="col_'+colsNum+'"><span  class="th">' + colArr[i].title + '：</span><span>' + (obj[colArr[i].field] || '') + (colArr[i].suffix ? colArr[i].suffix : '') + '</span></div>';

            }else if (singleLength % colsNum == 0){
                html += '<div class="col_'+colsNum+'"><span  class="th">' + colArr[i].title + '：</span><span>' + (obj[colArr[i].field] || '') + (colArr[i].suffix ? colArr[i].suffix : '') + '</span></div>';
                html += '</div>';
            }else {
                html += '<div class="col_'+colsNum+'"><span  class="th">' + colArr[i].title + '：</span><span>' + (obj[colArr[i].field] || '') + (colArr[i].suffix ? colArr[i].suffix : '') + '</span></div>';
            }

            
        }
    }
    $(id).html(html);
    var $imageViewer = $('#imageViewer');
    $('.imgs_con img').click(function(){
        $('.imgs_con').viewer('destroy');
        var viewer = $imageViewer.data('viewer');
        $('.imgs_con').viewer();
    })
}

$$.title2Table = function (id, colArr, obj,colsNum) {
    var html = '';
    colArr = colArr || [];
    obj = obj || {};
    var singleLength = 0,colsNum = colsNum||2;
    for (var i = 0; i < colArr.length; i++) {
        if(colArr[i].fitWidth){
            if (singleLength % colsNum != 0){
                html += '</div>';
            }
            singleLength = 0;
            html += '<div class="row">';
            if(colArr[i].type && colArr[i].type == 'img'){
                var imgs = obj[colArr[i].field].split(',');
                html += '<div class="col_'+colsNum+' fit_Width"><span class="th">' + colArr[i].title + '</span>';
                html += '<div class="imgs_con">'
                $.each(imgs,function(i,item){
                    html += '<img class="img" src="'+(item)+'" width="80px"/>'
                })
                html += '</div>'
                html += '</div>';
            }else{
                html += '<div class="col_'+colsNum+' fit_Width"><span class="th">' + colArr[i].title + '</span><span>' + (obj[colArr[i].field] || '') + (colArr[i].suffix ? colArr[i].suffix : '') + '</span></div>';
            }
            html += '</div>';
            // console.log(singleLength)

        }else{
            // console.log(singleLength)
            singleLength++;
            if (singleLength % colsNum == 1){
                html += '<div class="row">';
                html += '<div class="col_'+colsNum+'"><span  class="th">' + colArr[i].title + '</span><span>' + (obj[colArr[i].field] || '') + (colArr[i].suffix ? colArr[i].suffix : '') + '</span></div>';

            }else if (singleLength % colsNum == 0){
                html += '<div class="col_'+colsNum+'"><span  class="th">' + colArr[i].title + '</span><span>' + (obj[colArr[i].field] || '') + (colArr[i].suffix ? colArr[i].suffix : '') + '</span></div>';
                html += '</div>';
            }else {
                html += '<div class="col_'+colsNum+'"><span  class="th">' + colArr[i].title + '</span><span>' + (obj[colArr[i].field] || '') + (colArr[i].suffix ? colArr[i].suffix : '') + '</span></div>';
            }

            
        }
    }
    $(id).html(html);
    var $imageViewer = $('#imageViewer');
    $('.imgs_con img').click(function(){
        $('.imgs_con').viewer('destroy');
        var viewer = $imageViewer.data('viewer');
        $('.imgs_con').viewer();
    })
}

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function moreThanTen(num) {
    return num >= 10 ? num : '0' + num;
}
var fontSize = $$.fitFontSize(18);
function setBarOrLine(id, data, option,clickFun) {
    option = option || {};
    var elem = $(id)[0];
    var myChart = echarts.getInstanceByDom(elem) || echarts.init(elem);
    var datas = data.series,
        series = [],
        unit = data.unit;
    var color = option.color || [
        {color2:'',color1:'#15C0FF'},
        {color2:'',color1:'#34C39D'},
        {color2:'',color1:'#FF6169'},
        {color2:'',color1:'#FFBD1E'},
    ];
    var chartType = '';
    datas.map((item, i) => {
        chartType = item.type||'line'
        series.push({
            animation: true ,
            name: item.name,
            stack: item.stack || '',
            type: item.type,
            data: item.data,
            barWidth: option.barWidth||10,
            // barMinHeight: (option.barWidth||10)/3,
            itemStyle: {
                color: item.type=='line'?color[i].color1:new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: color[i].color1
                    },
                    {
                        offset: 1,
                        color: color[i].color2||color[i].color1
                    }
                ])
            },
            yAxisIndex: item.yAxisIndex||0,
            symbol: 'circle',
            symbolSize: 4,
            smooth:true,
            lineStyle: {
                width: 2,
                color: color[i].color1,
            },
        })
    })
    var myOption = {
        grid: {
            left: 0,
            top:  $$.transVHFontSize(1.7+1.7),
            bottom: 0,
            right: 0,
            containLabel: true,
        },
        tooltip: {
            show: true,
            trigger: 'axis',
            confine:true
        },
        legend: {
            show: true,
            left:option.twoYAxis?'center':'right',
            top:0,
            itemWidth: $$.transVHFontSize(1.2),
            itemHeight: $$.transVHFontSize(.8),
            itemGap: $$.transVHFontSize(2),
            textStyle: {
                fontSize: fontSize,
                color: '#fff',
            },
        },
        xAxis: [
            {

                type: 'category',
                axisLabel: {
                    interval:0,
                    formatter: '{value} ',
                    color: '#ffffff',
                    textStyle: {
                        fontSize: fontSize,
                    },
                    rotate: option.xAxisRotate||0
                },
                boundaryGap: true,
                interval:0,
                data: data.categories,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "#4F6776"
                    },
                },
                axisTick: {
                    show:  true,
                    lineStyle: {
                        color: "#4F6776",
                    },
                },
                splitLine: {
                    show: option["yAxisSplitLineShow"] || false,
                    lineStyle: {
                        type: "dotted",
                        width: 0.5,
                        color: "#4F6776",
                    },
                },
            },
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    formatter: '{value} ',
                    color: '#ffffff',
                    textStyle: {
                        fontSize: fontSize,
                    },
                },
                name: unit[0] ? '单位：' + unit[0] : "",
                nameGap: $$.transVHFontSize(1.2),
                nameTextStyle: {
                    //   align: "right",
                    fontSize: fontSize,
                    color: "#fff",
                },
                axisLabel: {
                    show: true,
                    fontSize: fontSize,
                    color: "#fff",
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "#4F6776"
                    },
                },
                axisTick: {
                    show:  true,
                    lineStyle: {
                        color: "#4F6776",
                    },
                },
                splitLine: {
                    show:  false,
                    lineStyle: {
                        type: "dotted",
                        width: 0.5,
                        color: "#4F6776",
                    },
                },
            },
            {
                show: option.twoYAxis||false,
                type: 'value',
                axisLabel: {
                    formatter: '{value} ',
                    color: '#ffffff',
                    textStyle: {
                        fontSize: fontSize,
                    },
                },
                name: unit[1] ? '单位：' + unit[1] : "",
                nameGap: $$.transVHFontSize(1.2),
                nameTextStyle: {
                    //   align: "right",
                    fontSize: fontSize,
                    color: "#fff",
                },
                axisLabel: {
                    show: true,
                    fontSize: fontSize,
                    color: "#fff",
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "#4F6776"
                    },
                },
                axisTick: {
                    show:  true,
                    lineStyle: {
                        color: "#4F6776",
                    },
                },
                splitLine: {
                    show:  false,
                    lineStyle: {
                        type: "dotted",
                        width: 0.5,
                        color: "#4F6776",
                    },
                },
            },
        ],
        series: series,
    };
    myChart.setOption(myOption, true)
    myChart.off('click');
    myChart.on("click",function(params){
        var index = datas.map(item=>item.name).indexOf(params.name);
        if(index>-1){
            params.chartData = datas[index];
        }
        clickFun&&clickFun(params)
    })
}
function setLine(id, data, option,clickFun) {
    option = option || {};
    var elem = $(id)[0];
    var myChart = echarts.getInstanceByDom(elem) || echarts.init(elem);
    var datas = data.series,
        series = [],
        unit = data.unit;
    var color = option.color || ['#34C39D', '#8E67FF', '#2F9EFE'];
    var chartType = '';
    datas.map((item, i) => {
        chartType = item.type||'line'
        series.push({
            animation: true ,
            name: item.name,
            stack: item.stack || '',
            type: item.type||'line',
            data: item.data,
            // symbol: 'circle',
            symbol: 'emptyCircle',
            symbolSize: 4,
            smooth: option.notSmooth?false:true,
            barWidth: option.barWidth||10,
            // barMinHeight: (option.barWidth||10)/3,
            lineStyle: {
                width: 2,
                color: color[i]
            },
            itemStyle: {
                color: color[i]
            },
            areaStyle: {
                show: option.hideArea?false:true,
                color: color[i],
                opacity: option.hideArea?0:.2
            },
            label:{
                show:option.seriesLabel?true:false,
                position:'top',
                distance:1,
                textStyle:{
                    color: color[i],
                    fontSize: fontSize-2
                }
            }
        })
    })
    var myOption = {
        color: color,
        grid: {
            left:  '2%',
            right: '5%',
            top: series.length==1?$$.transVHFontSize(1.7+1.7):$$.transVHFontSize(6),
            bottom: '0',
            containLabel: true,
        },
        legend: {
            show: series.length==1?false:true,
            orient: "horizontal",
            top: 'top',
            left:"center",
            itemWidth: $$.transVHFontSize(1.2),
            itemHeight: $$.transVHFontSize(.8),
            itemGap: $$.transVHFontSize(2),
            textStyle: {
                fontSize: fontSize,
                color: '#fff'
            }
        },
        tooltip: {
            show: true,
            trigger: "axis",
            // formatter:  (params)=> {// tooltip的formatter
            //     var relVal = params[0].name
            //     for (var i = 0, l = params.length; i < l; i++) {
            //       let settingUnit = this.option.setting[i].yAxisName;
            //       let unit = settingUnit || this.option.yAxis && this.option.yAxis[params[i].seriesIndex] && this.option.yAxis[params[i].seriesIndex].name || this.option.yAxisName;
            //         relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + params[i].value + (unit||'')
            //     }
            //     return relVal
            // }
        },
        xAxis: [{
            type: "category",
            show: true,
            interval: 0,
            boundaryGap:chartType=='bar'?true:false,
            axisLabel: {
                show: true,
                fontSize: fontSize,
                color: "#fff",
                interval: option.interval||0,
                rotate: option.xAxisRotate||0,
                formatter: option.xAxisOverflow?function(params){
                    return params.length>3?params.substr(0,2)+'...':params;
                    return params.split('').join('\n')
                }:'{value}'
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: "#4F6776"
                },
            },
            axisTick: {
                show:  true,
                lineStyle: {
                    color: "#4F6776",
                },
            },
            splitLine: {
                show: option["yAxisSplitLineShow"] || false,
                lineStyle: {
                    type: "dotted",
                    width: 0.5,
                    color: "#4F6776",
                },
            },
            data: data.categories,
        }, ],
        yAxis: {
            show: true,
            type: "value",
            name: unit ? '单位：' + unit : "",
            nameGap: $$.transVHFontSize(1.2),
            nameTextStyle: {
                //   align: "right",
                fontSize: fontSize,
                color: "#fff",
            },
            axisLabel: {
                show: true,
                fontSize: fontSize,
                color: "#fff",
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: "#4F6776"
                },
            },
            axisTick: {
                show:  true,
                lineStyle: {
                    color: "#4F6776",
                },
            },
            splitLine: {
                show: option["yAxisSplitLineShow"] || false,
                lineStyle: {
                    type: "dotted",
                    width: 0.5,
                    color: "#4F6776",
                },
            },
        },
        series: series
    }
    myChart.setOption(myOption, true);
    myChart.off('click');
    myChart.on("click",function(params){
        var index = datas.map(item=>item.name).indexOf(params.name);
        if(index>-1){
            params.chartData = datas[index];
        }
        clickFun&&clickFun(params)
    })
}
function setPie(id, data, option,clickFun) {
    var elem = $(id)[0];
    var myChart = echarts.getInstanceByDom(elem) || echarts.init(elem);
    var datas = data.datas;
    var maxNameLength = ((datas.map(item => {
        var length = 0;
        for(var l=0;l<item.name.length;l++){
            if(/[\u4e00-\u9fa5]/.test(item.name[l])){
                length += 1;
            }else{
                length += .5;
            }
        }
        return length;
    })).sort(function (a, b) {
        return b - a;
    }))[0];
    
    var total = 0;
    datas.map(item => {
        total += item.value;
    })
    var series=[{
        type: "pie",
        radius: option.radius||['35%', '65%'],
        center: option.center||['20%', '50%'],
        roseType:option.roseType||false,
        name: data.name || '',
        label: {
            show: false
        },
        labelLine: {
            show: false
        },
        data: datas,
        hoverOffset:5,
        minAngle: 5 ,
        animation: true ,
    },]
    maxNameLength = (maxNameLength>10?10:maxNameLength)
    if(!option.normalPie){
    series.push({
        type: "pie",
        radius: ['35%', '38%'],
        center: option.center||['20%', '50%'],
        name: '',
        label: {
            show: false
        },
        labelLine: {
            show: false
        },
        data: [{
            value: 1,
            itemStyle: {
                color: '#fff'
            }
        }],
        hoverAnimation:false
    })
    }
    var myOption = {
        color: option.color || ['#2F9EFE', '#FDAE5A', '#FF6169', '#34C39D', '#2F9EFE', '#8E67FF','#FF8949', '#2F6EFE', '#1C9172', '#FFE2A4', '#2148A3', '#BB602E','#FFA0A5', '#C63E45', '#81F5FF', '#03EAFF', '#1CA63C', '#55BDC6','#87EA65', '#87EA65'],
        grid: {
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            containLabel: true,
        },
        tooltip:{
            show:true,
            formatter: '{b}<br />数值：{c}<br />占比：{d}%',
            confine: true,
            // padding:0
        },
        legend: {
            type:datas.length>8?'scroll':'plain',
            orient: "vertical",
            top: option.legendTop||'middle',
            left: option.legendLeft || "50%",
            itemWidth: $$.transVHFontSize(1.5),
            itemHeight: $$.transVHFontSize(1.1),
            // itemGap: option.legendItemGap || $$.transVHFontSize(1),
            itemGap: option.legendItemGap || $$.transVHFontSize(1.1),
            padding: 0,
            textStyle: {
                fontSize: fontSize,
                color: '#fff',
                rich: {
                    name: {
                        fontSize: fontSize,
                        width: maxNameLength * fontSize
                    },
                    value: {
                        fontSize: fontSize,
                        color: '#fff'
                    },
                    percent: {

                    }
                }
            },
            // formatter:datas.length>8?'{name}':
            formatter: function (name) {
                var showValue = option.showValue || false,
                    showPercent = option.showPercent || false;
                var index = datas.map(item => item.name).indexOf(name);
                if (name && index > -1) {
                    var value = datas[index].value,
                        percent = (value / total * 100).toFixed(option.fixedNum || 2);
                    return [
                        '{name|' + (name.length>10?name.substr(0,9)+'...':name) + '} ',
                        showValue ? '{value|' + (value + (data.unit || '')) + '} ' : '',
                        showPercent ? '{percent|(' + (percent + '%') + ')}' : '',
                    ].join('')
                } else {
                    return name
                }
            },
            pageIconSize: $$.transVHFontSize(1),
            pageIconColor: '#2f4554' ,
            pageIconInactiveColor: '#fff' ,
            pageTextStyle:{
                fontSize: fontSize,
                color: '#fff',
            }
        },
        series:series,
        // series: [{
        //         type: "pie",
        //         radius: option.radius||['35%', '65%'],
        //         center: option.center||['25%', '50%'],
        //         name: data.name || '',
        //         label: {
        //             show: false
        //         },
        //         labelLine: {
        //             show: false
        //         },
        //         data: datas,
        //         hoverOffset:5,
        //         minAngle: 5 ,
        //         animation: true ,
        //     },
        //     {
        //         type: "pie",
        //         radius: ['35%', '38%'],
        //         center: option.center||['25%', '50%'],
        //         name: '',
        //         label: {
        //             show: false
        //         },
        //         labelLine: {
        //             show: false
        //         },
        //         data: [{
        //             value: 1,
        //             itemStyle: {
        //                 color: '#fff'
        //             }
        //         }],
        //         hoverAnimation:false
        //     },
        // ]
    }
    myChart.setOption(myOption, true);
    // myChart.off('click');
    // myChart.on('click',function(params){
    //     // clickFun&& clickFun(params)
    // });
    myChart.off("legendselectchanged");
    myChart.on("legendselectchanged",function(params){
        console.log(params)
        var isSelected = params.selected[params.name];
        if(isSelected == false){
            myChart.dispatchAction({
                type:'legendToggleSelect',
                name: params.name
            });
            myChart.dispatchAction({
                type:'highlight ',
                name: params.name
            });
            var index = datas.map(item=>item.name).indexOf(params.name);
            if(index>-1){
                params.dataIndex = index;
                params.chartData = datas[index];
            }
            clickFun&& clickFun(params)
        }
    });
}
function initNewsList(id,datas,columns,clickFun,noHead,showPage,notScroll){
    window[id+'NewsTimer'] = null;
    clearInterval(window[id+'NewsTimer']);
    var pageSize=showPage&&showPage.pageSize||5,pageIndex = 0;
    var html = '<div class="t_tr">暂无数据！</div>';
    if(datas && datas.length>0){
        $(id).html(`<div class="thead"></div>
                <div class="tbody">
                    <div class="real_table"></div>
                </div>`);
        html = '';
        var theadHTML = '';
        $.each(columns,function(i,item){
            theadHTML += '<div class="text_overflow">'+item.title+'</div>'
        });
        $(id+' .thead').html(`<div class="t_tr">${theadHTML}</div>`);
        if(showPage){
            $(id).addClass('news_list_page')
            $(id).append('<div class="pagenation"></div>');
            var pageHTML='',
            pages = Math.ceil(datas.length/pageSize);
            while(pages>0){
                pageHTML += '<span></span>';
                pages--;
            };
            setData(pageIndex);
            scroll();
            $(id+' .pagenation').html(pageHTML);
            $(id+' .pagenation span').eq(0).addClass('active');
            $(id+' .pagenation span').click(function(){
                clearInterval(window[id+'NewsTimer']);
                pageIndex = $(this).index();
                setData(pageIndex);
            });
            $(id).mouseover(function(){
                clearInterval(window[id+'NewsTimer']);
            }).mouseout(function(){
                clearInterval(window[id+'NewsTimer']);
                scroll();
            });
            function scroll(){
                window[id+'NewsTimer'] = setInterval(function(){
                    pageIndex ++;
                    if(pageIndex >= Math.ceil(datas.length/pageSize)){
                        pageIndex = 0;
                    };
                    setData(pageIndex);
                },5000);
            }
        }else{
            pageSize = datas.length;
            setData(0);
            if(!notScroll){
                $(id+' .real_table').scrollTable({
                    interval: 80,
                    step: 1
                });
            }
            
        }
        
        if(noHead){
            $(id+' .thead').remove();
            $(id).find('.text_overflow').addClass('ellipsis2');
            $(id).find('.text_overflow').parent().css('background-color','transparent').css('margin-bottom','2vh');
        }
        $(id+' .real_table').find('.t_tr>div').off('click')
        $(id+' .real_table').find('.t_tr>div').click(function(e){
            var index = $(this).parent().attr('data-index');
            var field = $(this).attr('data-field');
            clickFun && clickFun(datas[index],field)
        });
    }else{
        $(id).html(html);
    }
    function setData(pageIndex){
        var dataHTML = '';
        var i = 0;
        var data = datas.slice(pageIndex*pageSize,(pageIndex+1)*pageSize);
        while(i<data.length){
            var tr = '';
            var item = data[i];
            var index = pageIndex*pageSize+i;
            $.each(columns,function(colIndex,colItem){
                if(colItem.type == 'index'){
                    tr += `<div class="text_overflow" data-field="${colItem.field}" title="${ (colItem.preffix||'')+(index+1) }"><i class="">${ (colItem.preffix||'')+(index+1) }</i></div>`
                }else if(colItem.type == 'pm'){
                    tr += `<div class="text_overflow" data-field="${colItem.field}" title="${ (colItem.preffix||'')+(index+1) }"><i class="pm pm_${index}">${ (colItem.preffix||'')+(index+1) }</i></div>`
                }else if(colItem.type == 'num'){
                    tr += `<div class="text_overflow" data-field="${colItem.field}" title="${ hasProp(item,colItem.field)+(colItem.suffix||'') }"><i class="num white">${ hasProp(item,colItem.field) }</i>${ (colItem.suffix||'') }</div>`
                }else{
                    tr += `<div class="text_overflow ${colItem.type || ''}" data-field="${colItem.field}" title="${ hasProp(item,colItem.field)+(colItem.suffix||'') }" style="text-align:${colItem.align|| 'center'};">${ hasProp(item,colItem.field)+(colItem.suffix||'') }</div>`
                }
            })
            dataHTML += `<div class="t_tr" data-index="${ index }">${tr}</div>`
            i++;
        };
        $(id+' .real_table').html(dataHTML);
        $(id+' .real_table').find('.t_tr>div').off('click');
        $(id+' .real_table').find('.t_tr>div').click(function(e){
            var index = $(this).parent().attr('data-index');
            var field = $(this).attr('data-field');
            clickFun && clickFun(datas[index],field)
        });
        $(id+' .pagenation span').eq(pageIndex).addClass('active').siblings().removeClass('active');
    }

}
function hasProp(obj,field,defaultValue){
    if(obj.hasOwnProperty(field)){
        return obj[field];
    }else{
        return defaultValue||'';
    }
}